var list = [];
var app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    images_arr: [],
    nameStatus: false,
    nameId: '',
    name: '',
    nameText: '',
    idNumber: '', //IC卡号
    //
    categoryStatus: false,
    categoryName: '',
    categoryIdOne: '',
    categoryIdTwo: '',
    objectMultiArray: [],
    multiIndex: [0, 0],
    multiArray: [],
    //
    weight: '', //毛重
    weightTare: '', //车重
    weightOne: '', //扣重
    weightTwo: '', //扣点
    weightNet: '', //净重
    price: '', //单价
    countPrice: 0.0, //总价
    orderType: 3,
    supplierPackerId: ''
  },
  onLoad: function(options) {
    var that = this;
    console.log('onLoad值', options.supplierId);
    console.log('onLoad值', options.supplierPackerId);
    if (options.supplierId != undefined && options.name != undefined) {
      that.setData({
        nameId: options.supplierId, //供应商用户ID
        nameText: options.name, //供应商姓名
        nameStatus: true,
        //orderType: 3,
        orderType: 2,
        supplierPackerId: options.supplierPackerId
      });
    } else {
      that.setData({
        orderType: 3
      });
    }
  },
  onShow: function(options) {
    console.log('qqqq', options);
    this.getOne();
  },

  goSupplier: function() {
    wx.navigateTo({
      url: 'supplier?orderByHand=' + 1
    });
  },

  //选择品类
  getOne() {
    var that = this;
    wx.showLoading({
      title: '拼命加载中'
    });
    wx.request({
      method: 'POST',
      url: app.preUrl + 'getListCategory',
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        userId: app.globalData.userId
      },
      success: function(res) {
        wx.hideLoading();
        let data = res.data.result;
        console.log(res.data.result);
        let arrO = [];
        let arrT = [];
        data.forEach((item, index) => {
          arrO.push(item.name);
        });
        data[0].categoryList.forEach((item, index) => {
          arrT.push(item.name);
        });
        let newmultiArray = [arrO, arrT];
        console.log(newmultiArray);
        that.setData({
          objectMultiArray: res.data.result,
          multiArray: newmultiArray
        });
      },
      fail: function(error) {
        console.log(error);
      }
    });
  },
  //品类选择
  bindMultiPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value);
    var that = this;
    that.setData({
      multiIndex: e.detail.value,
      categoryStatus: true,
      categoryIdOne: that.data.objectMultiArray[e.detail.value[0]].categoryId,
      categoryIdTwo:
        that.data.objectMultiArray[e.detail.value[0]].categoryList[
          e.detail.value[1]
        ].categoryId,
      categoryName:
        that.data.objectMultiArray[e.detail.value[0]].categoryList[
          e.detail.value[1]
        ].name
    });
    console.log(this.data.multiIndex);
    console.log(
      '一级品类id',
      that.data.objectMultiArray[e.detail.value[0]].categoryId
    ); //一级品类id
    console.log(
      '二级品类id',
      that.data.objectMultiArray[e.detail.value[0]].categoryList[
        e.detail.value[1]
      ].categoryId
    ); //
  },
  bindMultiPickerColumnChange: function(e) {
    var that = this;
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value);

    switch (e.detail.column) {
      case 0:
        list = [];
        for (var i = 0; i < that.data.objectMultiArray.length; i++) {
          if (
            that.data.objectMultiArray[i].categoryId ==
            that.data.objectMultiArray[e.detail.value].categoryId
          ) {
            for (
              let j = 0;
              j < that.data.objectMultiArray[i].categoryList.length;
              j++
            ) {
              list.push(that.data.objectMultiArray[i].categoryList[j].name);
            }
          }
        }
        that.setData({
          'multiArray[1]': list,
          'multiIndex[0]': e.detail.value,
          'multiIndex[1]': 0
        });
    }
  },
  //上传图片
  upload: function(item) {
    var that = this;
    wx.showLoading({
      title: '上传中'
    });
    wx.uploadFile({
      url: app.preUrl + 'uploadFile',
      header: {
        'Content-Type': 'multipart/form-data'
      },
      filePath: item,
      name: 'file',
      formData: {
        userId: app.globalData.userId //附加信息为用户ID
      },
      success: function(res) {
        console.log(res);
        wx.hideLoading();
        var imgUrl =
          'https://www.lvdaxia.com.cn/dabaozhan/fileImage/' +
          JSON.parse(res.data).result;
        that.setData({
          images_arr: that.data.images_arr.concat(imgUrl)
        });
      }
    });
  },
  upimg: function() {
    let that = this;
    let len = 0;
    len = 4 - this.data.images_arr.length;
    if (len == 0) {
      wx.showToast({
        title: '最多上传4张图片',
        icon: 'loading',
        duration: 1500
      });
      return;
    }
    wx.chooseImage({
      count: len,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        const tempFilePaths = res.tempFilePaths;
        console.log(res);
        tempFilePaths.forEach(function(item, index) {
          that.upload(item);
        });
      }
    });
  },

  // 删除图片
  deleteImg: function(e) {
    var that = this;
    var images = that.data.images_arr;
    var index = e.currentTarget.dataset.index;
    images.splice(index, 1);
    that.setData({
      images_arr: images
    });
  },

  //毛重
  onNumberWeight: function(e) {
    var that = this;
    that.setData({ weight: e.detail.value.replace(/[^\d.]/g, '') });
    that.setData({ weight: e.detail.value.replace(/\.{2,}/g, '.') });
    that.setData({
      weight: e.detail.value
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
    });
    that.setData({
      weight: e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
    });
    let weight = Number(this.data.weight); //毛重
    let weightOne = Number(this.data.weightOne); //车重
    if (weightOne != 0) {
      if (weight > weightOne) {
        let weightTwo = parseFloat((weightOne / weight) * 100).toFixed(2);
        that.setData({ weightTwo: weightTwo });
      } else {
        wx.showToast({
          title: '毛重不得小于车重',
          icon: 'none'
        });
      }
    }

    this.getJzWeight();
  },
  //车重
  onNumberWeightTare: function(e) {
    var that = this;
    that.setData({ weightTare: e.detail.value.replace(/[^\d.]/g, '') });
    that.setData({ weightTare: e.detail.value.replace(/\.{2,}/g, '.') });
    that.setData({
      weightTare: e.detail.value
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
    });
    that.setData({
      weightTare: e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
    });

    this.getJzWeight();
  },
  // 转化扣重
  onNumberWeightChange() {
    let weight = Number(this.data.weight); //毛重
    let weightOne = Number(this.data.weightOne); //扣重
    let weightTwo = Number(this.data.weightTwo); //扣点
    console.log(weight + ',' + weightOne + ',' + weightTwo);
  },
  //录入扣重
  onNumberWeightOne: function(e) {
    var that = this;
    that.setData({ weightOne: e.detail.value.replace(/[^\d.]/g, '') });
    that.setData({ weightOne: e.detail.value.replace(/\.{2,}/g, '.') });
    that.setData({
      weightOne: e.detail.value
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
    });
    that.setData({
      weightOne: e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
    });
    let weight = Number(this.data.weight); //毛重
    if (weight > 0) {
      let weightTwo = parseFloat((e.detail.value / weight) * 100).toFixed(2);
      that.setData({ weightTwo: weightTwo });
    }
    this.getJzWeight();
  },

  //录入扣点
  onNumberWeightTwo: function(e) {
    var that = this;
    that.setData({ weightTwo: e.detail.value.replace(/[^\d.]/g, '') });
    that.setData({ weightTwo: e.detail.value.replace(/\.{2,}/g, '.') });
    that.setData({
      weightTwo: e.detail.value
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
    });
    that.setData({
      weightTwo: e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
    });
    let weight = Number(this.data.weight); //毛重
    if (weight > 0) {
      let weightOne = parseFloat((e.detail.value * weight) / 100).toFixed(2);
      that.setData({ weightOne: weightOne });
    }
    this.getJzWeight();
  },
  getJzWeight() {
    //获取净重
    let weight = Number(this.data.weight); //毛重
    let weightTare = Number(this.data.weightTare); //车重
    let weightOne = Number(this.data.weightOne); //扣重
    // console.log(weight + ',' + weightTare + ',' + weightOne)

    let weightNet = weight - weightTare - weightOne;
    if (weightNet < 0) {
      this.setData({ weightNet: 0 });
    } else {
      this.setData({ weightNet: weightNet });
    }
    this.getCountPrice();
  },
  //录入单价
  onNumberPrice: function(e) {
    var that = this;
    that.setData({ price: e.detail.value.replace(/[^\d.]/g, '') });
    that.setData({ price: e.detail.value.replace(/\.{2,}/g, '.') });
    that.setData({
      price: e.detail.value
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
    });
    that.setData({
      price: e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
    });
    this.getCountPrice();
  },

  getCountPrice() {
    //获取总价
    let price = Number(this.data.price); //单价
    let weightNet = Number(this.data.weightNet); //净重
    let countPrice = price * weightNet;
    this.setData({ countPrice: parseFloat(countPrice).toFixed(2) });
  },
  bindFormSubmit: function(e) {
    var that = this;
    var nameId = that.data.nameId;
    var idNumber = that.data.idNumber;
    var categoryIdOne = that.data.categoryIdOne;
    var categoryIdTwo = that.data.categoryIdTwo;
    var weight = that.data.weight;
    var weightTare = that.data.weightTare;
    var weightOne = that.data.weightOne;
    var weightTwo = that.data.weightTwo;
    var netWeight = that.data.weightNet;
    var price = that.data.price;
    var status = e.currentTarget.dataset.status;
    console.log(weight + ',' + weightTare);
    if (!that.data.nameStatus) {
      wx.showToast({
        title: '供货人必选',
        icon: 'none'
      });
      return false;
    } else if (!that.data.categoryStatus) {
      wx.showToast({
        title: '回收类别必选',
        icon: 'none'
      });
      return false;
    } else if (!weight) {
      wx.showToast({
        title: '毛重必填',
        icon: 'none'
      });
      return false;
    } else if (!weightTare) {
      wx.showToast({
        title: '车重必填',
        icon: 'none'
      });
      return false;
    } else if (!weightOne || !weightTwo) {
      wx.showToast({
        title: '扣重/扣点必填',
        icon: 'none'
      });
      return false;
    } else if (!price) {
      wx.showToast({
        title: '核定单价必填',
        icon: 'none'
      });
      return false;
    } else {
      if (that.data.orderType == 3) {
        that.setData({
          supplierPackerId: wx.getStorageSync('supplierPackerId')
        });
      } else if (that.data.orderType == 2) {
        that.setData({
          supplierPackerId: that.data.supplierPackerId,
          orderType : 3
        });
      }
      wx.showLoading({ title: '提交中' });
      wx.request({
        method: 'POST',
        url: app.preUrl + 'addSiteOrder',
        dataType: 'json',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          userId: app.globalData.userId, //打包站用户ID
          supplierId: nameId, //供应商用户ID
          supplierPackerId: that.data.supplierPackerId,
          name: that.data.nameText, //供应商姓名
          supplierNumber: idNumber, //IC卡号
          parentId: categoryIdOne, //父品类ID
          categoryId: categoryIdTwo, //品类ID
          grossWeight: parseFloat(weight).toFixed(2), //毛重 保留两位小数
          tareWeight: parseFloat(weightTare).toFixed(2), //车重 保留两位小数
          offWeight: parseFloat(weightOne).toFixed(2), //扣重 保留两位小数 单位:公斤
          offPointsWeight: weightTwo, //扣重百分比 保留两位小数 20.34代表20.34%
          netWeight: parseFloat(netWeight).toFixed(2),
          price: parseFloat(price).toFixed(2), //单价 保留两位小数 单位:元
          moneyTotal: that.data.countPrice, //总价 保留两位小数 单位:元
          pictureList: that.data.images_arr,
          orderType: that.data.orderType
        },
        success: function(res) {
          wx.hideLoading();
          // console.log(res);
          if (res.data.code == 100) {
            let createTime = res.data.result.createTime;
            if (status == 1) {
              let data = {
                id: res.data.result.id,
                createTime: createTime,
                destination: that.data.nameText,
                supplierName: that.data.nameText,
                grossWeight: weight,
                tareWeight: weightTare,
                offWeight: weightOne,
                netWeight: that.data.weightNet,
                categoryName: that.data.categoryName,
                price: price,
                moneyTotal: that.data.countPrice
              }; //车重 //单价  //总价 //毛重
              wx.showToast({
                title: '提交成功',
                icon: 'success',
                duration: 1000
              });
              setTimeout(function() {
                wx.redirectTo({
                  url: 'payment?data=' + JSON.stringify(data)
                });
              }, 1500);
            } else {
              wx.showModal({
                content: '订单录入成功，进入“订单结算”可继续支付哦',
                confirmColor: '#50BEC5',
                confirmText: '知道了',
                showCancel: false,
                success(res) {
                  wx.redirectTo({ url: 'order' });
                }
              });
            }
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.message,
              confirmColor: '#56BDE0',
              showCancel: false
            });
            that.setData({ buthidden: false });
          }
        },
        fail: function(error) {
          console.log(error);
          that.setData({ buthidden: false });
        }
      });
    }
  }
});
